<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div style="border: 1px solid black; width: 500px; height: 200px;" id="message">

</div>

<textarea style="border:  1px solid aqua; width: 500px; height: 200px;" id="userinput">

</textarea>
<button id="send">发送</button>

<div>
    <p>当前选择的好友是：<i id="fuid"></i></p>
    <select name="friends" id="fri">
        <option value="001">001</option>
        <option value="002">002</option>
    </select>
    <button onclick="choose()">确认</button>
</div>
</body>
<script type="text/javascript" src="/js/jquery.min.js"></script>

<script type="text/javascript">

    var fuid;

    function choose() {
        fuid = $("#fri").val();
        $("#fuid").text(fuid);
    }

    $(function () {
        var socket = null;
        if ('WebSocket' in window) {
            console.log("浏览器支持websocket");
            socket = new WebSocket("ws://localhost:8080/websocket");
            var fromUserId = '${Session.userId!""}';

            $("#send").on('click', function () {
                var content = $("#userinput").val();
                var msg = {"fromUserId": fromUserId, "content": content, "toUserId": fuid}
                socket.send(JSON.stringify(msg));
                $("#message").append("<p align='right'>" + "我： " + content + "</p>")
                $("#userinput").val("");
            })

            //连接打开事件
            socket.onopen = function () {
                console.log("Socket 已打开");
               /* var msg = {"fromUserId": fromUserId, "content": "测试群发消息"}
                var msgStr = JSON.stringify(msg);
                socket.send(msgStr);*/
            };
            //收到消息事件
            socket.onmessage = function (msg) {
                var msgStr = msg.data;
                var obj = JSON.parse(msgStr);
                console.log(obj);
                $("#message").append("<p>" + "收到来自" + obj.fromUserId + "的消息：" + obj.content + "</p>")
            };
            //连接关闭事件
            socket.onclose = function () {
                console.log("Socket已关闭");
            };
            //发生了错误事件
            socket.onerror = function () {
                alert("Socket发生了错误");
            }

            //窗口关闭时，关闭连接
            window.unload = function () {
                socket.close();
            };
        } else
            alert("您的浏览器不支持websocket");
    })
</script>
</html>